﻿using Arim.Utils.Network;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace Arim.Evms.Web
{
    public class WSRtspContext
    {
        WebSocket _ws;
        bool _dataChannel;
        bool quitFlag = false;
        public WSRtspContext(WebSocket ws, RtspProxy rtsp, bool dataChannel)
        {
            _ws = ws;
            Rtsp = rtsp;
            _dataChannel = dataChannel;
        }

        public string ControlWebSocketId { get; set; }

        public string DataWebSocketId { get; set; }

        public RtspProxy Rtsp { get; private set; }

        public string Seq
        {
            get;set;
        }

        public async Task Send(byte[] buffer)
        {
            await Rtsp.Send(buffer);
        }

        public async Task StartReceive()
        {
            quitFlag = false;
            while (!quitFlag)
            {
                List<byte[]> datas;
                bool succeed;
                if (_dataChannel)
                    succeed = Rtsp.TryDequeData(out datas, 10);
                else
                    succeed = Rtsp.TryDequeControl(out datas, 1);
                if (succeed)
                {
                    foreach(byte[] data in datas)
                    {
                        if (!_dataChannel)
                        {
                            WSRtspResponse response = new WSRtspResponse();
                            response.Seq = Seq;
                            response.RtspBuffer = data;
                            await _ws.SendAsync(response.ToArray(), _dataChannel ? WebSocketMessageType.Binary : WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                        else
                        {
                            await _ws.SendAsync(data, _dataChannel ? WebSocketMessageType.Binary : WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                    }
                }
                else
                {
                    if (_dataChannel)
                        await Task.Delay(1);
                    else
                        await Task.Delay(10);
                }
            }
        }

        public void StopReceive()
        {
            quitFlag = true;
        }
    }
}
